package com.controller;

import com.pojo.Contact;
import com.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping(value = "/contact")
public class UserController {
    @Autowired
    private ContactService contactService;

    /**
     * 分页查询所有联系人
     * 按照联系人姓名模糊查询
     * @param model
     * @param currentPageNo
     * @param cname
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(Model model,@RequestParam(defaultValue = "1") Integer currentPageNo ,String cname){

        Integer pageSize = 5;
        Integer pageIndex = (currentPageNo-1)*pageSize;
        int totalCount = contactService.count(cname);
        int totalPageCount = totalCount/pageSize;
        if (totalCount % 5 > 0){
            totalPageCount ++;
        }

        if (pageIndex>totalPageCount){
            pageIndex=totalPageCount;
        }
//        List<Contact> list = contactService.list(pageIndex,pageSize);
        List<Contact> list = contactService.sous(pageIndex,pageSize,cname);
        model.addAttribute("list",list);
        model.addAttribute("cname",cname);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("currentPageNo",currentPageNo);
        model.addAttribute("totalPageCount",totalPageCount);
        if (totalCount==0){
            model.addAttribute("error","没有找到与"+cname+"相关的联系人！");
        }
        return "index";
    }

    @RequestMapping(value = "/toAdd")
    public String toAdd(){
        return "add";
    }

    @RequestMapping(value = "/add")
    public String add(Contact contact){
        int result = contactService.add(contact);
        if (result>0){
            return "redirect:/contact/list";
        }
        return "add";
    }

    @RequestMapping(value = "byId")
    public String byId(Model model,Integer id){
        Contact contact = contactService.byId(id);
        model.addAttribute("contact",contact);
        return "update";
    }

    @RequestMapping(value = "/update")
    public String update(Contact contact){
        int result = contactService.update(contact);
        if (result>0){
            return "redirect:/contact/list";
        }
        return "update";
    }
}
